<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>SB集成Redis学习笔记之实际应用场景-java干货 | z77z的小码窝 | 年少无为，卖码为生。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="springboot,redis">
    <meta name="description" content="之前利用springBoot中的缓存机制，使用Redis作为缓存容器，做了一个缓存的简单Demo，当然Redis不仅仅可以用来做缓存的容器，还有很多开发的实际场景中会用到Redis的特性，通过几天的学习，现将学习的成果整理分享给大家。希望大家也多多讨论，提供跟多的使用场景，来熟练掌握在springboot中的使用。

个人博客：http://z77z.oschina.io/
此项目下载地址：ht">
<meta property="og:type" content="article">
<meta property="og:title" content="SB集成Redis学习笔记之实际应用场景-java干货">
<meta property="og:url" content="http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/index.html">
<meta property="og:site_name" content="z77z的小码窝">
<meta property="og:description" content="之前利用springBoot中的缓存机制，使用Redis作为缓存容器，做了一个缓存的简单Demo，当然Redis不仅仅可以用来做缓存的容器，还有很多开发的实际场景中会用到Redis的特性，通过几天的学习，现将学习的成果整理分享给大家。希望大家也多多讨论，提供跟多的使用场景，来熟练掌握在springboot中的使用。

个人博客：http://z77z.oschina.io/
此项目下载地址：ht">
<meta property="og:image" content="http://img.blog.csdn.net/20170206205428032?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjA5NTQ5NTk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:updated_time" content="2017-02-06T13:29:03.430Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SB集成Redis学习笔记之实际应用场景-java干货">
<meta name="twitter:description" content="之前利用springBoot中的缓存机制，使用Redis作为缓存容器，做了一个缓存的简单Demo，当然Redis不仅仅可以用来做缓存的容器，还有很多开发的实际场景中会用到Redis的特性，通过几天的学习，现将学习的成果整理分享给大家。希望大家也多多讨论，提供跟多的使用场景，来熟练掌握在springboot中的使用。

个人博客：http://z77z.oschina.io/
此项目下载地址：ht">
<meta name="twitter:image" content="http://img.blog.csdn.net/20170206205428032?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjA5NTQ5NTk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
    
        <link rel="alternative" href="/atom.xml" title="z77z的小码窝" type="application/atom+xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.4.3">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">邹海清</h5>
          <a href="mailto:1093615728@qq.com" title="1093615728@qq.com" class="mail">1093615728@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://git.oschina.net/z77z" target="_blank" >
                <i class="icon icon-lg icon-git"></i>
                git
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://t.qq.com/zouhaiqing123" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                微博
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/custom"  >
                <i class="icon icon-lg icon-link"></i>
                404页面测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">SB集成Redis学习笔记之实际应用场景-java干货</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">SB集成Redis学习笔记之实际应用场景-java干货</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-02-06T13:22:58.000Z" itemprop="datePublished" class="page-time">
  2017-02-06
</time>


            
        </h5>
    </div>

    

</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#Redis的特性"><span class="post-toc-number">1.</span> <span class="post-toc-text">Redis的特性</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景一：简单计数功能"><span class="post-toc-number">2.</span> <span class="post-toc-text">场景一：简单计数功能</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景二：按时间统计计数"><span class="post-toc-number">3.</span> <span class="post-toc-text">场景二：按时间统计计数</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景三：按模糊Key值查询"><span class="post-toc-number">4.</span> <span class="post-toc-text">场景三：按模糊Key值查询</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景五：使用hashs存储获取修改java对象"><span class="post-toc-number">5.</span> <span class="post-toc-text">场景五：使用hashs存储获取修改java对象</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景六：使用lists有序存储读取"><span class="post-toc-number">6.</span> <span class="post-toc-text">场景六：使用lists有序存储读取</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景七：使用sets存储读取-无序-去重-求差集，交集，并集"><span class="post-toc-number">7.</span> <span class="post-toc-text">场景七：使用sets存储读取 无序 去重 求差集，交集，并集</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#场景八：Sorted-Set-存取数据-排序"><span class="post-toc-number">8.</span> <span class="post-toc-text">场景八：Sorted Set 存取数据 排序</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-SB集成Redis学习笔记之实际应用场景-java干货"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">SB集成Redis学习笔记之实际应用场景-java干货</h1>
        <div class="post-meta">
            <time class="post-time" title="2017年02月06日 21:22" datetime="2017-02-06T13:22:58.000Z"  itemprop="datePublished">2017-02-06</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <blockquote>
<p>之前利用springBoot中的缓存机制，使用Redis作为缓存容器，做了一个缓存的简单Demo，当然Redis不仅仅可以用来做缓存的容器，还有很多开发的实际场景中会用到Redis的特性，通过几天的学习，现将学习的成果整理分享给大家。希望大家也多多讨论，提供跟多的使用场景，来熟练掌握在springboot中的使用。</p>
</blockquote>
<p>个人博客：<a href="http://z77z.oschina.io/">http://z77z.oschina.io/</a></p>
<p>此项目下载地址：<a href="https://git.oschina.net/z77z/springboot_mybatisplus" target="_blank" rel="external">https://git.oschina.net/z77z/springboot_mybatisplus</a></p>
<h1 id="Redis的特性"><a href="#Redis的特性" class="headerlink" title="Redis的特性"></a>Redis的特性</h1><ul>
<li><p><strong>Strings</strong>：Strings 数据结构是简单的key-value类型，value其实不仅是String，也可以是数字.<br>常用命令:  set,get,decr,incr,mget 等。<br>常用方法：</p>
<ol>
<li>获取字符串长度</li>
<li>往字符串append内容</li>
<li>设置和获取字符串的某一段内容</li>
<li>设置及获取字符串的某一位（bit）</li>
<li>批量设置一系列字符串的内容</li>
</ol>
</li>
<li><p><strong>Hashs</strong>：Redis Hash对应Value内部实际就是一个HashMap，常用命令：hget,hset,hgetall 等。</p>
</li>
<li><p><strong>Lists</strong>：Redis list的实现为一个双向链表，即可以支持反向查找和遍历，更方便操作，不过带来了部分额外的内存开销，Redis内部的很多实现，包括发送缓冲队列等也都是用的这个数据结构。<br>常用命令：lpush,rpush,lpop,rpop,lrange等。</p>
</li>
<li><p><strong>Sets</strong>：Sets 集合的概念就是一堆不重复值的组合。Redis还为集合提供了求交集、并集、差集等操作，可以非常方便的实现如共同关注、共同喜好、二度好友等功能。<br>常用命令：sadd,spop,smembers,sunion 等。</p>
</li>
<li><p><strong>Sorted Sets</strong>：Redis sorted set的使用场景与set类似，区别是set不是自动有序的。sorted set可以通过用户额外提供一个优先级(score)的参数来为成员排序，并且是插入有序的，即自动排序。<br>常用命令：zadd,zrange,zrem,zcard等</p>
</li>
</ul>
<blockquote>
<p>下面就根据这几个特性，也就是Redis支持的数据类型，来完成以下场景的实现。</p>
</blockquote>
<h1 id="场景一：简单计数功能"><a href="#场景一：简单计数功能" class="headerlink" title="场景一：简单计数功能"></a>场景一：简单计数功能</h1><blockquote>
<p>Redis是一个很好的计数器，计数器是 Redis 的原子性自增操作可实现的最直观的模式了，它的想法相当简单：每当某个操作发生时，向 Redis 发送一个 INCR 命令。使用场景比如网站的访问数，注册用户数，文章的点赞数，高并发的秒杀活动，分布式序列号生成等等统计计数的功能实现。Redis 解决这类计数问题得心应手，相比关系数据库速度更快，消耗资源更少。还可以通过set()方法来重置计数。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 简单计数</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			ValueOperations&lt;String, String&gt; opsForValue = stringRedisTemplate.opsForValue();</div><div class="line">			<span class="comment">//计数前打印</span></div><div class="line">			System.out.println(opsForValue.get(<span class="string">"test1"</span>));</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</div><div class="line">				<span class="comment">//计数，第一个参数为key值，第二个参数为每次增加计数的单位</span></div><div class="line">				opsForValue.increment(<span class="string">"test1"</span>, <span class="number">1</span>);</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//计数后打印</span></div><div class="line">			System.out.println(opsForValue.get(<span class="string">"test1"</span>));</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景二：按时间统计计数"><a href="#场景二：按时间统计计数" class="headerlink" title="场景二：按时间统计计数"></a>场景二：按时间统计计数</h1><blockquote>
<p>有时候除了简单的计数外，比如注册用户数需要按日统计，处理方法比较简单，把日期带入计数器 key 就可以。以此类推，还可以按其他方式进行统计计数，只需要把统计的方式添加到key值就可以了</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 按时间计数 </span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="comment">//将日期添加到key值中</span></div><div class="line">		String key = <span class="string">"test2_"</span> + <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>).format(<span class="keyword">new</span> Date());</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			ValueOperations&lt;String, String&gt; opsForValue = stringRedisTemplate.opsForValue();</div><div class="line">			System.out.println(opsForValue.get(key));</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</div><div class="line">				opsForValue.increment(key, <span class="number">1</span>);</div><div class="line">			&#125;</div><div class="line">			System.out.println(opsForValue.get(key));</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景三：按模糊Key值查询"><a href="#场景三：按模糊Key值查询" class="headerlink" title="场景三：按模糊Key值查询"></a>场景三：按模糊Key值查询</h1><blockquote>
<p>在按条件统计计数的时候，把时间加入到了key值中，有时候要只是查询某个对象的统计数时，就可以使用模糊Key值查询。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 模糊K值查询</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test3</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			ValueOperations&lt;String, String&gt; opsForValue = stringRedisTemplate.opsForValue();</div><div class="line">			<span class="comment">//先获取前缀为test的Key值列表。</span></div><div class="line">			Set&lt;String&gt; keys = stringRedisTemplate.keys(<span class="string">"test*"</span>);</div><div class="line">			<span class="comment">//遍历满足条件的Key值获取对应的value值</span></div><div class="line">			<span class="keyword">for</span> (String a : keys) &#123;</div><div class="line">				System.out.println(a + <span class="string">":"</span> + opsForValue.get(a));</div><div class="line">			&#125;</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>场景四：设置Key的有效时间（防止高并发访问）</p>
<blockquote>
<p>在redis中可以设置key值的有效时间，用户访问链接的时候，将用户的唯一信息比如ip地址等为key值，时间为value值，在redis中记录一下，在用户再次访问的时候，通过key值获取前一次访问的时间，比较时间的间隔，如果低于阀值，就拒绝这次请求，防止用户多次访问。这里只是写下在spring的RedisTemplate接口怎么使用。具体的逻辑实现自己搞定。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 设置key值的有效时间</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test4</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			ValueOperations&lt;String, String&gt; opsForValue = stringRedisTemplate.opsForValue();</div><div class="line">			opsForValue.set(<span class="string">"test4"</span>, <span class="string">"test4"</span>);</div><div class="line">			System.out.println(opsForValue.get(<span class="string">"test4"</span>));</div><div class="line">			<span class="comment">// TimeUnit.SECONDS:解释定时参数的单位</span></div><div class="line">			<span class="comment">// MICROSECONDS 微秒 一百万分之一秒（就是毫秒/1000）</span></div><div class="line">			<span class="comment">// MILLISECONDS 毫秒 千分之一秒</span></div><div class="line">			<span class="comment">// NANOSECONDS 毫微秒 十亿分之一秒（就是微秒/1000）</span></div><div class="line">			<span class="comment">// SECONDS 秒</span></div><div class="line">			<span class="comment">// MINUTES 分钟</span></div><div class="line">			<span class="comment">// HOURS 小时</span></div><div class="line">			<span class="comment">// DAYS 天</span></div><div class="line">			<span class="keyword">if</span>(stringRedisTemplate.expire(<span class="string">"test4"</span>, <span class="number">5</span>, TimeUnit.SECONDS))&#123;</div><div class="line">				System.out.println(<span class="string">"设置过期时间成功,等待。。。。"</span>);</div><div class="line">				Thread.sleep(<span class="number">5001</span>);</div><div class="line">			&#125;</div><div class="line">			System.out.println(opsForValue.get(<span class="string">"test4"</span>));</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景五：使用hashs存储获取修改java对象"><a href="#场景五：使用hashs存储获取修改java对象" class="headerlink" title="场景五：使用hashs存储获取修改java对象"></a>场景五：使用hashs存储获取修改java对象</h1><blockquote>
<p>在实际开发中，我们经常将一些结构化的信息打包成HashMap，在客户端序列化后存储为一个字符串的值，比如用户的昵称、年龄、性别、积分等，这时候在需要修改其中某一项时，通常需要将所有值取出反序列化后，修改某一项的值，再序列化存储回去。这样不仅增大了开销，也不适用于一些可能并发操作的场合（比如两个并发的操作都需要修改积分）。</p>
<p>而Redis的Hash结构可以使你像在数据库中Update一个属性一样只修改某一项属性值。因为Redis的Hash结构是以对象的名字作为redis的key值，以对象的唯一属性值作为hash的key值，以对象来作为redis的value值。结构图如下：</p>
</blockquote>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="http://img.blog.csdn.net/20170206205428032?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjA5NTQ5NTk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="hashs存储结构图" title="">
                </div>
                <div class="image-caption">hashs存储结构图</div>
            </figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 使用hashs存储获取对象</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test5</span><span class="params">()</span></span>&#123;</div><div class="line">		BeautifulPictures beautifulPictures = beautifulPicturesService.selectById(<span class="number">1</span>);</div><div class="line">		HashOperations&lt;String, Object, BeautifulPictures&gt; hash = redisTemplate.opsForHash();</div><div class="line">		hash.put(<span class="string">"test5"</span>,beautifulPictures.getId(),beautifulPictures);</div><div class="line">		System.out.println(hash.get(<span class="string">"test5"</span>, beautifulPictures.getId()));</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景六：使用lists有序存储读取"><a href="#场景六：使用lists有序存储读取" class="headerlink" title="场景六：使用lists有序存储读取"></a>场景六：使用lists有序存储读取</h1><blockquote>
<p>适用于获取最近N个操作的数据。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//使用lists存储读取 有序</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test6</span><span class="params">()</span></span>&#123;</div><div class="line">		ListOperations&lt;String, String&gt; list = stringRedisTemplate.opsForList();</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"1"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"2"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"3"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"4"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"5"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"6"</span>);</div><div class="line">		list.leftPush(<span class="string">"test6"</span>, <span class="string">"7"</span>);</div><div class="line">		<span class="comment">//保持链表只有3位</span></div><div class="line">		list.trim(<span class="string">"test6"</span>, <span class="number">0</span>, <span class="number">2</span>);</div><div class="line">		System.out.println(list.range(<span class="string">"test6"</span>, <span class="number">0</span>, list.size(<span class="string">"test6"</span>)-<span class="number">1</span>));</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景七：使用sets存储读取-无序-去重-求差集，交集，并集"><a href="#场景七：使用sets存储读取-无序-去重-求差集，交集，并集" class="headerlink" title="场景七：使用sets存储读取 无序 去重 求差集，交集，并集"></a>场景七：使用sets存储读取 无序 去重 求差集，交集，并集</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//使用set存储读取  无序 去重  求差集，交集，并集</span></div><div class="line">	<span class="meta">@Test</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test7</span><span class="params">()</span></span>&#123;</div><div class="line">		SetOperations&lt;String, String&gt; set = stringRedisTemplate.opsForSet();</div><div class="line">		set.add(<span class="string">"test7_1"</span>, <span class="string">"2"</span>, <span class="string">"1"</span>,<span class="string">"2"</span>,<span class="string">"3"</span>,<span class="string">"4"</span>,<span class="string">"4"</span>,<span class="string">"3"</span>);</div><div class="line">		set.add(<span class="string">"test7_2"</span>, <span class="string">"2"</span>, <span class="string">"6"</span>,<span class="string">"2"</span>,<span class="string">"3"</span>,<span class="string">"7"</span>,<span class="string">"6"</span>,<span class="string">"5"</span>);</div><div class="line">		System.out.println(<span class="string">"全部成员"</span>+set.members(<span class="string">"test7_1"</span>));</div><div class="line">		System.out.println(<span class="string">"差集"</span>+set.difference(<span class="string">"test7_1"</span>, <span class="string">"test7_2"</span>));</div><div class="line">		System.out.println(<span class="string">"交集"</span>+set.intersect(<span class="string">"test7_1"</span>, <span class="string">"test7_2"</span>));</div><div class="line">		System.out.println(<span class="string">"并集"</span>+set.union(<span class="string">"test7_1"</span>, <span class="string">"test7_2"</span>));</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h1 id="场景八：Sorted-Set-存取数据-排序"><a href="#场景八：Sorted-Set-存取数据-排序" class="headerlink" title="场景八：Sorted Set 存取数据 排序"></a>场景八：Sorted Set 存取数据 排序</h1><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">//Sorted Set 存取数据 排序  相比sets 保存时多一个权重参数score，相当于按照此参数来排序</div><div class="line">	@Test</div><div class="line">	public void test8()&#123;</div><div class="line">		ZSetOperations&lt;String, String&gt; zSet = stringRedisTemplate.opsForZSet();</div><div class="line">		zSet.add(&quot;test8&quot;, &quot;use1&quot;, 9);</div><div class="line">		zSet.add(&quot;test8&quot;, &quot;use2&quot;, 1);</div><div class="line">		zSet.add(&quot;test8&quot;, &quot;use3&quot;, 5);</div><div class="line">		zSet.add(&quot;test8&quot;, &quot;use4&quot;, 9);</div><div class="line">		//对应的score值增加</div><div class="line">		//zSet.incrementScore(&quot;test8&quot;, &quot;use1&quot;, 1);</div><div class="line">		System.out.println(zSet.reverseRange(&quot;test8&quot;, 0, zSet.size(&quot;test8&quot;)-1));</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-02-06T13:29:03.430Z" itemprop="dateUpdated">2017年2月6日 21:29</time>
</span><br>


        如要转载请注明出处：<a href="/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/" target="_blank" rel="external">http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/</a>
    </div>
    <footer>
        <a href="http://z77z.oschina.io">
            <img src="/img/avatar.jpg" alt="邹海清">
            邹海清
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/redis/">redis</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springboot/">springboot</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&title=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&pic=http://z77z.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&title=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&via=http://z77z.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/02/13/SpringBoot+shiro整合学习之登录认证和权限控制/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">SpringBoot+shiro整合学习之登录认证和权限控制</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/01/30/SpringBoot缓存注解学习笔记之Redis/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">SpringBoot缓存注解学习笔记之Redis</h4>
      </a>
    </div>
  
</nav>



    

<div class="comments" id="comments">
    <div class="ds-thread" data-thread-key="SB集成Redis学习笔记之实际应用场景-java干货" data-title="SB集成Redis学习笔记之实际应用场景-java干货" data-url="http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/"></div>
</div>
<script>
lazyScripts.push('//cdn.bootcss.com/marked/0.3.6/marked.min.js');

var duoshuoQuery = {short_name:'z77z', theme: 'none'};
lazyScripts.push('/js/embed.min.js?v=1.4.3');


</script>







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        我只要一角钱~ ~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.png" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            <span>博客内容遵循 <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">知识共享 署名 - 非商业性 - 相同方式共享 4.0协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://git.oschina.net/z77z" target="_blank">邹海清</a></span>
            <span>z77z的小码窝 &copy; 2016 - 2017</span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&title=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&pic=http://z77z.oschina.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&title=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《SB集成Redis学习笔记之实际应用场景-java干货》 — z77z的小码窝&url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/&via=http://z77z.oschina.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://z77z.oschina.io/2017/02/06/SB集成Redis学习笔记之实际应用场景-java干货/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



lazyScripts.push('//s95.cnzz.com/z_stat.php?id=1261081671&web_id=1261081671')

</script>

<script src="/js/main.min.js?v=1.4.3"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.4.3" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>


</body>
</html>
